#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
|===== Conference Bot Plugin ============
|= Timer Events
|===== By: ==============================
|= Patrick Kennedy
|===== Current Version: =================
|= 1.0
|===== Description: =========================================
|= These events will run at regular intervals.
|===== Additional Comments: =================================
|= 
|============================================================"""

from utils import isplugin, getjid, getdisplayname
from ini import userlist, database

global watch_list
watch_list = database["watched"]

def init(bot):
	if isplugin("watch"):
		bot.addTimer(2, timer_statuscheck, type = "seconds")
		
def unload(bot):
	if isplugin('watch'):
		bot.removeTimer('timer_statuscheck')

def timer_statuscheck(bot):
	watch_list = database["watched"]
	roster = bot.getRoster()
	for jid in bot.getRoster():
		jid = getjid(jid)
		if jid not in roster:
			continue

		jidStatus = bot.getJidStatus(jid).items()
		
		#last_status is the status of the user the last time the fucntion was run.
		#If the user doesn't have a status they are marked as "offline"
		global last_status
		last_status = userlist[jid]["jabberstatus"] or "offline"
		
		for user,(status,display) in jidStatus:
			user = getjid(user)
			if not watch_list[jid]:
				userlist[user]["jabberstatus"] = status
				continue
			if status != last_status and watch_list.has_key(user):
				sub_watched_status(bot, user, status)
			break
		else:
			if watch_list.has_key(jid):
				sub_watched_status(bot, jid, "offline")

			
def sub_watched_status(bot, user, status):
	#This is the translation table.
	trans_table = {
					'online' : 'Available', 
					'chat' : 'Available', 
					'dnd' : 'Busy', 
					'xa' : 'Idle',
					'away' : 'Away',
					'offline' : 'Offline'
					}
	#This is the "translation" of the jabber status.
	readable_status = "Unknown"
	
	#Check if there's a change.
	if status != last_status:
		#Check if the user just came online or not.
		if status in ["online","chat"] and last_status not in ["online","chat"]:
			if last_status == "offline":
				readable_status = "Online"
			else:
				readable_status = "Available"
		#For every other status, just get the translation from the table.
		else:
			readable_status = trans_table.get(status, 'Unknown')
	
	for watcher in watch_list.get(user):
		if readable_status is not "Unknown":
			bot.msg(watcher, "%s is now '%s'." % (getdisplayname(user), readable_status))
	#Set the status for later checks.
	userlist[user]["jabberstatus"] = status
